# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 配置模型
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, Enum, JSON
from sqlalchemy.orm import relationship
from .base import BaseModel
import enum


class FieldType(enum.Enum):
    """字段类型"""
    TEXT = 'text'  # 文本
    NUMBER = 'number'  # 数字
    EMAIL = 'email'  # 邮箱
    PHONE = 'phone'  # 电话
    DATE = 'date'  # 日期
    SELECT = 'select'  # 下拉选择
    RADIO = 'radio'  # 单选
    CHECKBOX = 'checkbox'  # 复选
    TEXTAREA = 'textarea'  # 多行文本
    FILE = 'file'  # 文件上传


class ValidationType(enum.Enum):
    """验证类型"""
    REQUIRED = 'required'  # 必填
    MIN_LENGTH = 'min_length'  # 最小长度
    MAX_LENGTH = 'max_length'  # 最大长度
    PATTERN = 'pattern'  # 正则表达式
    MIN_VALUE = 'min_value'  # 最小值
    MAX_VALUE = 'max_value'  # 最大值
    EMAIL_FORMAT = 'email_format'  # 邮箱格式
    PHONE_FORMAT = 'phone_format'  # 电话格式
    CUSTOM = 'custom'  # 自定义验证


class ConfigType(enum.Enum):
    """配置类型"""
    SYSTEM = 'system'  # 系统配置
    USER = 'user'  # 用户配置
    SCALE = 'scale'  # 量表配置
    PAYMENT = 'payment'  # 支付配置
    EMAIL = 'email'  # 邮件配置
    SMS = 'sms'  # 短信配置
    STORAGE = 'storage'  # 存储配置
    SECURITY = 'security'  # 安全配置


class BasicInfoConfig(BaseModel):
    """基本信息配置"""
    __tablename__ = 'basic_info_configs'
    
    # 字段信息
    field_name = Column(String(50), nullable=False, comment='字段名称')
    field_label = Column(String(100), nullable=False, comment='字段标签')
    field_type = Column(Enum('text', 'select', 'radio', 'checkbox', 'textarea', 'number', 'date', 'email', name='field_type_enum'), nullable=False, comment='字段类型')
    
    # 选项和验证
    has_options = Column(Boolean, default=False, comment='是否有选项')
    default_value = Column(String(255), comment='默认值')
    placeholder = Column(String(255), comment='占位符')
    has_validation = Column(Boolean, default=False, comment='是否有验证规则')
    
    # 验证设置
    is_required = Column(Boolean, default=False, comment='是否必填')
    
    # 显示控制
    is_visible = Column(Boolean, default=True, comment='是否可见')
    sort_order = Column(Integer, default=0, comment='排序')
    
    # 状态控制
    status = Column(Enum('active', 'inactive', name='basic_info_status'), default='active', comment='状态')
    
    # 关系
    options = relationship('FieldOption', back_populates='config', cascade='all, delete-orphan')
    validation_rules = relationship('ValidationRule', back_populates='config', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<BasicInfoConfig {self.field_name}: {self.field_label}>'


class FieldOption(BaseModel):
    """字段选项"""
    __tablename__ = 'field_options'
    
    config_id = Column(Integer, ForeignKey('basic_info_configs.id'), nullable=False, comment='配置ID')
    option_value = Column(String(200), nullable=False, comment='选项值')
    option_label = Column(String(200), nullable=False, comment='选项标签')
    
    # 显示设置
    is_default = Column(Boolean, default=False, comment='是否默认选项')
    is_active = Column(Boolean, default=True, comment='是否启用')
    sort_order = Column(Integer, default=0, comment='排序')
    
    # 额外属性
    icon = Column(String(100), comment='图标')
    color = Column(String(20), comment='颜色')
    description = Column(Text, comment='描述')
    
    # 关系
    config = relationship('BasicInfoConfig', back_populates='options')
    
    def __repr__(self):
        return f'<FieldOption {self.option_value}: {self.option_label}>'


class ValidationRule(BaseModel):
    """验证规则"""
    __tablename__ = 'validation_rules'
    
    config_id = Column(Integer, ForeignKey('basic_info_configs.id'), nullable=False, comment='配置ID')
    validation_type = Column(Enum(ValidationType), nullable=False, comment='验证类型')
    
    # 验证参数
    validation_value = Column(String(500), comment='验证值')
    error_message = Column(String(500), comment='错误消息')
    
    # 验证设置
    is_active = Column(Boolean, default=True, comment='是否启用')
    priority = Column(Integer, default=0, comment='优先级')
    
    # 关系
    config = relationship('BasicInfoConfig', back_populates='validation_rules')
    
    def __repr__(self):
        return f'<ValidationRule {self.validation_type.value}: {self.validation_value}>'


class AgreementContent(BaseModel):
    """协议内容"""
    __tablename__ = 'agreement_contents'
    
    # 基本信息
    title = Column(String(200), nullable=False, comment='协议标题')
    content = Column(Text, nullable=False, comment='协议内容')
    version = Column(String(20), default='1.0', comment='版本号')
    
    # 协议类型
    agreement_type = Column(String(50), nullable=False, comment='协议类型')
    
    # 状态设置
    is_active = Column(Boolean, default=True, comment='是否启用')
    is_required = Column(Boolean, default=True, comment='是否必须同意')
    
    # 时间信息
    effective_date = Column(DateTime, comment='生效日期')
    expiry_date = Column(DateTime, comment='失效日期')
    
    # 显示设置
    sort_order = Column(Integer, default=0, comment='排序')
    
    def __repr__(self):
        return f'<AgreementContent {self.title} v{self.version}>'
    
    @property
    def is_effective(self):
        """是否有效"""
        now = datetime.utcnow()
        if self.effective_date and now < self.effective_date:
            return False
        if self.expiry_date and now > self.expiry_date:
            return False
        return self.is_active


class SystemConfig(BaseModel):
    """系统配置"""
    __tablename__ = 'system_configs'
    
    # 配置信息
    config_key = Column(String(100), nullable=False, unique=True, comment='配置键')
    config_value = Column(Text, comment='配置值')
    config_type = Column(Enum(ConfigType), nullable=False, comment='配置类型')
    
    # 配置描述
    name = Column(String(200), comment='配置名称')
    description = Column(Text, comment='配置描述')
    
    # 数据类型
    value_type = Column(String(20), default='string', comment='值类型')
    default_value = Column(Text, comment='默认值')
    
    # 验证设置
    validation_rule = Column(Text, comment='验证规则')
    allowed_values = Column(JSON, comment='允许的值')
    
    # 显示设置
    is_public = Column(Boolean, default=False, comment='是否公开')
    is_editable = Column(Boolean, default=True, comment='是否可编辑')
    sort_order = Column(Integer, default=0, comment='排序')
    
    # 分组
    group_name = Column(String(100), comment='分组名称')
    
    def __repr__(self):
        return f'<SystemConfig {self.config_key}: {self.config_value}>'
    
    def get_typed_value(self):
        """获取类型化的值"""
        if not self.config_value:
            return self.get_typed_default_value()
        
        try:
            if self.value_type == 'int':
                return int(self.config_value)
            elif self.value_type == 'float':
                return float(self.config_value)
            elif self.value_type == 'bool':
                return self.config_value.lower() in ('true', '1', 'yes', 'on')
            elif self.value_type == 'json':
                import json
                return json.loads(self.config_value)
            else:
                return self.config_value
        except (ValueError, TypeError):
            return self.get_typed_default_value()
    
    def get_typed_default_value(self):
        """获取类型化的默认值"""
        if not self.default_value:
            return None
        
        try:
            if self.value_type == 'int':
                return int(self.default_value)
            elif self.value_type == 'float':
                return float(self.default_value)
            elif self.value_type == 'bool':
                return self.default_value.lower() in ('true', '1', 'yes', 'on')
            elif self.value_type == 'json':
                import json
                return json.loads(self.default_value)
            else:
                return self.default_value
        except (ValueError, TypeError):
            return None
    
    def set_typed_value(self, value):
        """设置类型化的值"""
        if value is None:
            self.config_value = None
            return
        
        if self.value_type == 'json':
            import json
            self.config_value = json.dumps(value, ensure_ascii=False)
        else:
            self.config_value = str(value)